package com.marver.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * 构造jwt及解析jwt的帮助类
 * @author kaede
 *
 */
public class JwtHelper {  
    public static Claims parseJWT(String jsonWebToken, String base64Security){  
        try  
        {  
            Claims claims = Jwts.parser()  
                       .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))  
                       .parseClaimsJws(jsonWebToken).getBody();  
            return claims;  
        }  
        catch(Exception ex)  
        {  
            return null;  
        }  
    }  
      
    /**
     * 生成JWT
     * @param appId 应用id
     * @param userId 用户ID
     * @param authcode 安全码
     * @param issuer  jwt签发者
     * @param TTLMillis  jwt的过期时间
     * @param base64Security
     * @return
     */
    public static String createJWT(String remoteIp,String appId, String userId,
            String issuer, long TTLMillis, String base64Security,String authcode)
    {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;  
           
        long nowMillis = System.currentTimeMillis();  
        Date now = new Date(nowMillis);  
           
        //生成签名密钥  
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);  
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());  
           
          //添加构成JWT的参数  
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                                        .claim("appid", appId)
                                        .claim("custid", userId)
                                        .claim("ip", remoteIp)
                                        .claim("authcode", authcode)
                                        .setAudience(String.valueOf(nowMillis))
                                        .setIssuer(issuer)
                                       // .setAudience(audience)
                                        .signWith(signatureAlgorithm, signingKey);
         //添加Token过期时间  
        if (TTLMillis >= 0) {  
            long expMillis = nowMillis + TTLMillis;  
            Date exp = new Date(expMillis);  
            builder.setExpiration(exp).setNotBefore(now);  
        }  
           
         //生成JWT  
        return builder.compact();  
    }   
} 